package com.fingard.dsp.bank.directbank.vbao01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.VerifyState;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthentication;
import com.fingard.dsp.bank.reqrespobj.auth.ReqAuth;
import com.fingard.dsp.bank.reqrespobj.auth.ReqQryAuth;
import com.fingard.dsp.bank.reqrespobj.auth.RetAtsAuth;
import com.fingard.dsp.bank.reqrespobj.auth.detail.RetAtsAuthDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.AuthenticationRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.TradeCodeEnum;

public class VBAO01Authentication extends VBAO01Base implements IAuthentication {
	@Override
	public RetAtsAuth dealAuth(ReqAuth p_reqAuth) throws Exception {
		RetAtsAuth retAts = new RetAtsAuth(p_reqAuth.reqHeader);
		RetAtsAuthDetail tmpRetDetail = new RetAtsAuthDetail();
		
		try {
			String authMerId = getBankConfig().getValueAsString("authMerId");
			if (StringHelper.hasAnyChar(authMerId)) {
				ActSetItem actItem = getBankConfig().getActSetItem(authMerId, "auth");
				if (actItem != null) {
					AuthenticationRequest authenticationRequest = new AuthenticationRequest();
			 		
					authenticationRequest.setVersion("6.0");
					authenticationRequest.setInputCharset(getCharset());
					authenticationRequest.setSignType("MD5");
			 		authenticationRequest.setCustomerNo(actItem.merchantId);
			 		authenticationRequest.setGoodNo(getBankConfig().getValueAsString("GoodNo"));
			 		authenticationRequest.setOrderNo(p_reqAuth.authDetail.askNumber);
			 		
			 		String bankCode = getBankConfig().getValueAsString("authBankCode");
			 		if (StringHelper.isNullOrEmpty(bankCode)) {
			 			WriteBankLogLn("配置文件缺失'<authBankCode></authBankCode>'节点配置!");
			 		}
			 		authenticationRequest.setBankCode(bankCode);
			 		
			 		String cardType = p_reqAuth.authDetail.cardType;
			 		if ("1".equals(cardType)) {
			 			cardType = "1";
			 		} else if ("3".equals(cardType) || "4".equals(cardType)) {
			 			cardType = "2";
			 		} else {
			 			cardType = "0";
			 		}
			 		authenticationRequest.setBankCardType(cardType);
			 		authenticationRequest.setBankCardNo(p_reqAuth.authDetail.authAct);
			 		authenticationRequest.setBankCardName(p_reqAuth.authDetail.authName);
			 		authenticationRequest.setCertType(convertCertTypeToBank(p_reqAuth.authDetail.certType));
			 		authenticationRequest.setCertId(p_reqAuth.authDetail.certNum);
			 		authenticationRequest.setMobile(p_reqAuth.authDetail.cellPhone);
					authenticationRequest.setCreditValid("");
					authenticationRequest.setCreditCvv2("");
					
					// 鉴权类型：1卡号、姓名、证件号、手机号 四要素验证, 2卡号、姓名、证件号三要素验证 ,3卡号、姓名二要素验证   暂时只支持1，2  两种类型
					String authType = "";
					if ("4".equals(p_reqAuth.authDetail.validElement)) {
						authType = "1";
					} else if ("3".equals(p_reqAuth.authDetail.validElement)) {
						authType = "2";
					} else {
						authType = "3";
					}
					authenticationRequest.setvType(authType);
					
					VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
				 	TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler.creatRequestXml(authenticationRequest, actItem.saltKey, getCharset(),TradeCodeEnum.SINGLE_AUTHENTICATION.getCode());
				 	WriteBankLogLn2("发送微保请求报文明文:" + tradeRequestXml.getOriRequestXml());
					WriteBankLogStep2(tradeRequestXml.getRequestXml());
				 	
			 		if(tradeRequestXml.getErrMsg() == null)	{
			 			String postReqUrl = bankFront.getUrl("realAuth");
						WriteBankLogLn2("微保鉴权提交服务地址: " + postReqUrl);

						String returnDKPayxml = vbaoChargeSystemHandler.http(postReqUrl,tradeRequestXml.getRequestXml(),getCharset());
						WriteBankLogLn2("微保返回报文密文:" + returnDKPayxml);
						
						String returnOriDKPayxml = Base64vbao.decode(returnDKPayxml, getCharset());
						//returnOriDKPayxml = new String(returnOriDKPayxml.getBytes(), getCharset());
						WriteBankLogStep3(returnOriDKPayxml);

						StringBuilder tmpSbMsg = new StringBuilder();
						XmlTextReader tmpBkReader = loadBankRespXmlReader(returnOriDKPayxml, tmpSbMsg);
						if (tmpBkReader != null) {
							tmpRetDetail.respCode = "0";
							tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");

							String tmpRespCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
							if ("T".equals(tmpRespCode)) {
								tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/TResponse/ValidationInfo/OrderNo");
								tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ValidationInfo/PayInfo");
			            		
								String authStatus = tmpBkReader.getFirstText("/TResponse/ValidationInfo/PayStatus");
				            	if ("1".equals(authStatus)) {
				            		tmpRetDetail.verifyState = VerifyState.SUCCESS;
				            		tmpRetDetail.originalCode = "00000";
				            		tmpRetDetail.originalInfo = "验证信息匹配";
				            		tmpRetDetail.unifiedCode = "EA001";
				            		tmpRetDetail.unifiedInfo = "验证信息匹配";
				            	} else {
				            		tmpRetDetail.verifyState = VerifyState.FAIL;
				            		tmpRetDetail.failType = "1";
				            		tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ValidationInfo/PayInfo");
				            		tmpRetDetail.originalCode = "B9011";
				            		tmpRetDetail.originalInfo = "认证失败，详见返回的错误信息描述";
				            		tmpRetDetail.unifiedCode = "EA066";
				            		tmpRetDetail.unifiedInfo = "认证失败，详见返回的错误信息描述";
				            	}
							} else {
								tmpRetDetail.verifyState = VerifyState.FAIL;
			            		tmpRetDetail.failType = "1";
			            		tmpRetDetail.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
			            		tmpRetDetail.originalCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
			            		tmpRetDetail.originalInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
			            		tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("AuthMapping", tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode"));
			            		tmpRetDetail.unifiedInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
							}
						} else {
							tmpRetDetail.respCode = "-1";
							tmpRetDetail.respInfo = tmpSbMsg.toString();
						}
			 		} else {
			 			tmpRetDetail.respCode = "-1";
			 			tmpRetDetail.respInfo = tradeRequestXml.getErrMsg();
			 		}
				} else {
					tmpRetDetail.respCode = "0";
					tmpRetDetail.respInfo = "未找到账号:[" + authMerId + "]商户配置信息";
					tmpRetDetail.verifyState = VerifyState.FAIL;
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "微保鉴权默认商户号:[" + authMerId + "]内容为空!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_reqAuth.authDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsAuth dealQryAuth(ReqQryAuth p_reqAuth) throws Exception {
		RetAtsAuth retAts = new RetAtsAuth(p_reqAuth.reqHeader);
		
		RetAtsAuthDetail tmpRetDetail = new RetAtsAuthDetail();
		tmpRetDetail.reqSeqID = p_reqAuth.askNumber;
		tmpRetDetail.respCode = "0";
		tmpRetDetail.respInfo = "暂不支持此接口:" + p_reqAuth.reqHeader.transType;
		retAts.writeRetDetail(tmpRetDetail);
		
		return retAts;
	}
}
